package chapter09.collection;

import org.jetbrains.annotations.NotNull;

import java.util.Comparator;
import java.util.Objects;
import java.util.TreeSet;

/**
 * TreeSet 有序集的学习
 * 创建两个有序集
 * 一个按编号和描述排序 同时也是自定义对象的默认排序
 * 一个按自定义比较器排序
 *
 * @author  insight
 * @since 2021/1/26
 */
public class Test03_TreeSet {
    public static void main(String[] args) {
        var sortById = new TreeSet<Item>();
        sortById.add(new Item(9012, "Modem"));
        sortById.add(new Item(1234, "Toaster"));
        sortById.add(new Item(5678, "Widget"));
        System.out.println(sortById);

        var sortByDesc = new TreeSet<Item>(Comparator.comparing(Item::getDesc));
        sortByDesc.addAll(sortById);
        System.out.println(sortByDesc);
    }
}

/**
 * 一个Item类 带有编号和描述
 */
class Item implements Comparable<Item> {
    private int id;
    private String desc;

    public Item() {}

    /**
     * 构造一个Item
     *
     * @param id 产品编号
     * @param desc 产品描述
     */
    public Item(int id, String desc) {
        this.id = id;
        this.desc = desc;
    }

    public String getDesc() { return desc; }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Item item = (Item) o;
        return id == item.id &&
                Objects.equals(desc, item.desc);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, desc);
    }

    @Override
    public String toString() {
        return "Item{" +
                "id=" + id +
                ", desc='" + desc + '\'' +
                '}';
    }

    @Override
    public int compareTo(@NotNull Item o) {
        int dif = Integer.compare(this.id, o.id);
        return dif != 0 ? dif : this.desc.compareTo(o.desc);
    }
}
